<?php
class LogAction extends Action {
        /**
         * 记录日志表
         * @param string  module                     运营用户的操作模块
         * @param integer moduleId                   module的id(已经没用了，但为了兼容以前的调用未去掉)
         * @param string  module_name                module的name
         * @param string  op                         操作的类型
         * @param string  content_sql                操作的sql语句
         * @param string  content                    操纵的内容
         * */
    public function add($module,$moduleId = '',$module_name,$op,$content_sql,$content='') {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $groupModel = M('module_group');
        Session::switchCustomer($cid);
        $LogModel = M("log");
        $groupId = $groupModel->where(['group' => $module])->getField('id');
        $moduleId = $groupId;
        $data["loginName"] = Session::$user["loginName"];
        $data["cid"] = Session::$user["customerId"];
        $data["cus_user_id"] = Session::$user["id"];
        $data["cus_user_fullName"] = Session::$user["fullName"];
        $data["module"] = $module;
        $data["moduleId"] = $moduleId;
        $data["module_name"] = $module_name;
        //判断$op的类型
        if($op == 'add'){
            $op = '添加';
        }else if($op == 'update'){
            $op = '更新';
        }else if($op == 'delete'){
            $op = '删除';
        }else if($op == 'find'){
            $op = '查询';
        }else if($op == 'login'){
            $op = '登录';
        }else if($op == 'changePsw'){
            $op = '修改密码';
        }else if($op == 'bindWxNum'){
            $op = '绑定微信号';
        }else if($op == 'unBindWxNum'){
            $op = '解绑微信号';
        }else if($op=='other'){
            $op = '其他';
        }
        $data["op"] = $op;
        if (empty($content)){
            $data["content"] = Session::$user["fullName"].'用户'.$op.$module_name;
        }else{
            $data["content"] = $content;
        }

        $data['content_sql'] = $content_sql;
        //获取用户的ip
        if($_SERVER['HTTP_HTTP_X_REAL_IP']){
            //nginx 代理模式下，获取客户端真实IP
            $realIp = $_SERVER['HTTP_HTTP_X_REAL_IP'];
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            //客户端的ip
            $realIp = $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['HTTP_HTTP_X_FORWARDED_FOR'])) {
            //浏览当前页面的用户计算机的网关
            $arr = explode(',', $_SERVER['HTTP_HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $realIp = trim($arr[0]);
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            //浏览当前页面的用户计算机的ip地址
            $realIp = $_SERVER['REMOTE_ADDR'];
        }else{
            $realIp=$_SERVER['REMOTE_ADDR'];
        }
        $data['ip'] = $realIp;
        $data["createTime"] = date("Y-m-d H:i:s");

        $LogModel->add($data);
    }

    /**
     * joymap操作日志及搜索
     * $search             搜索条件
     * $module_name        搜索模块名称
     * $beginTime          搜索时间
     */
    public function logList($search = '', $module = '', $beginTime = '', $endTime = '', $orderBy = 'desc', $order = 'createTime', $start = 0, $limit = 10, $excel = 0)
    {
        /**  */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**  */
        $LogModel = M("log");
        Session::switchCustomer(0);
        $userId     = Session::$user['id'];
        $customerId = Session::$user['customerId'];
        $Model_GroupUser      = M('group_user');
        Session::switchCustomer($customerId);

        /** 过滤条件 */
        // 模块
        !empty($module) ? $where['moduleId'] = $module :'';
        // 搜索条件
        if ($search != '') {
            $where['content'] = array('like', '%' . $search . '%');
        }
        // 时间
        if ($beginTime != '' && $endTime != '') {
            $beginTime = $beginTime . ' 00:00:00';
            $endTime   = date('Y-m-d H:i:s', strtotime($endTime . ' +1 day'));
            $where['createTime'] = array(array('egt', $beginTime), array('elt', $endTime));
        } else if ($beginTime != '') {
            $beginTime = $beginTime . ' 00:00:00';
            $where["createTime"] = array('egt', $beginTime);
        } else if ($endTime != '') {
            $endTime = date('Y-m-d H:i:s', strtotime($endTime . ' +1 day'));
            $where["createTime"] = array('elt', $endTime);
        }
        // 用户层级筛选, 考虑组级的关系: 用户只能看到自己的操作日志，组长可以看到组员的日志
        $Where_GroupUser = [
            'userId'    => $userId,
            'leader'    => 1
        ];
        $infoIds = $Model_GroupUser->where($Where_GroupUser)->getField('infoId', true); // 这里的infoId是组id, 这里获取的是以这个用户为组长的组
        if (empty($infoIds)) {  // 如果以他为组长的组为空, 则组员只有自己
            $userIds = [ $userId ];   // 为了与下面统一, 这里也写成一个数组

        } else {
            // 获得以该用户为组长的所有组的所有组员, 这里必然会有用户id重复, 所以在下面做了去重
            $userIds = $Model_GroupUser->where(['infoId' => array('in', $infoIds)])->getField('userId', true);
            $userIds = array_keys(array_flip($userIds));    // 数组去重
        }
        $where['cus_user_id']   = array('in', $userIds);

        /** 数据筛选 */
        $arr = $LogModel->order($order.' '.$orderBy)->where($where)->limit($start, $limit)->select();
        if ($excel) {
            $arr = $LogModel->order($order.' '.$orderBy)->where($where)->select();
            $this->exportExcel($arr);
            return;
        }

        /** 返回 */
        if ($arr) {
            $count = $LogModel->where($where)->count();
            Output::instance()->objArray($arr, $count);
        } else {
            $return = [
                'code'  => 2,
                'msg'   => '记录不存在'
            ];
            Output::instance()->objArray($return);
        }
    }

    //老平台的操作日志列表
    public function index($loginName='',$search='',$module='',$op='',$startDate = '', $endDate = '', $start = 0, $limit = 25) {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $LogModel = M("log");
        !empty($search) ? $where['module_name'] = $search :'';
        !empty($loginName) ? $where['loginName'] = $loginName :'';
        !empty($module) ? $where['module'] = $module :'';
        $loginName = trim($loginName);$module = trim($module);$op = trim($op);$search = trim($search);
        !empty($op) ? $where['op'] = $op :'';
        if ($startDate != '' && $endDate != '') {
            $where['createTime'] = array(array('egt',$startDate),array('elt',$endDate));
        } else if ($startDate != '') {
            $where["createTime"] = array('egt', $startDate);
        } else if ($endDate != '') {
            $where["createTime"] = array('elt', $endDate);
        }
        if (!isset($where)) {
            $arr = $LogModel->order("createTime desc")->limit($start, $limit)->select();
        } else {
            $arr = $LogModel->order("createTime desc")->where($where)->limit($start, $limit)->select();
        }
        if ($arr) {
            if (!isset($where)) {
                $count = $LogModel->count();
            } else {
                $count = $LogModel->where($where)->count();
            }
            Output::instance()->objArray($arr, $count);
        } else {
            Output::instance()->resultCode();
        }
    }

    /*
     * 用户操作日志导出
     * $expTitle         表格里面的表头
     * $expCellName      表格数据描述，即表头
     * $$expTableData    表格数据
     * */
    public function exportExcel($expTableData){
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $fileName = '操作日志信息'.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $expCellName  = array(
            array('id','序号'),
            array('cus_user_fullName','用户名'),
            array('module_name','模块名'),
            array('op','操作类型'),
            array('content','操作'),
            array('createTime','添加时间'),
        );

        $expTableDataTemp = array();
        foreach ($expTableData as $key => $value) {
            $expTableDataTemp[] = $value;
        }
        if($expTableDataTemp){
            Output::instance()->objArrayExcel($fileName,$expCellName,$expTableDataTemp);
        }

    }

    /**
     * 模块下拉搜索
     * @param $backend 此处传nmp（新后台）
     *
     */
    public function moduleList($search='',$backend='nmp'){
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
//      开放平台 - 查数据库secret
        Session::switchCustomer(0);
//      实例化开发平台数据模型
        $module_group = D('module_group');
        $customer_module_group = D('customer_module_group');
        if(!empty($search)){
            $where['b.name']= array("like","%".trim($search)."%");
        }
        Session::switchCustomer($customerId);
//        $where['backend']=array('eq',$backend);
//        $where['pid']=array('neq',0);
//        $where['display']=array('eq',1);
        $where['a.customerId']=array('eq',$customerId);
        $where['a.permission']=array('eq','allow');
        $arr=$customer_module_group->alias('a')->where($where)->join('wx_module_group as b on a.group=b.group')->field('b.id,b.name')->select();
//        $arr=$module_group->where($where)->field('id,name')->select();
        if($arr) {
            Output::instance()->objArray($arr);
        }
        else {
            Output::instance()->resultCode(code_success);
        }
    }



}




